package com.example.workmode.Content;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;


public class DataProvider extends ContentProvider{

	private static final int TASK_LIST = 1;
	private static final int TASK_ID = 2;

	private static final UriMatcher uri_matcher;
	static
	{
		uri_matcher = new UriMatcher(UriMatcher.NO_MATCH);
		uri_matcher.addURI(TaskContract.AUTHORITY, TaskContract.Task.PATH, TASK_LIST);
		uri_matcher.addURI(TaskContract.AUTHORITY, TaskContract.Task.PATH + "/#", TASK_ID);
	}

	private static String LOG_TAG = "workmode";

	// database
	private SQLiteDatabase datab;

	private static final String DATABASE_NAME = "todoList";
	private static final String DATABASE_TABLE = "item";
	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_CREATE = 
			"create table " + DATABASE_TABLE + 
			" (" + TaskContract.Task._ID + 
			" integer primary key autoincrement, " +
			TaskContract.Task.NAME + " text not null, " +
			TaskContract.Task.DUEDATE + " text not null, " +
			TaskContract.Task.TODAY + " text not null);";


	private static class DatabaseHelper extends SQLiteOpenHelper
	{
		DatabaseHelper(Context context)
		{
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db)
		{
			db.execSQL(DATABASE_CREATE);	
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
		{
			Log.w(LOG_TAG, "upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}

	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#delete(android.net.Uri, java.lang.String, java.lang.String[])
	 */
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2)
	{
		int count = 0;
		switch(uri_matcher.match(arg0))
		{
		case TASK_LIST:
			count = datab.delete(DATABASE_TABLE, arg1, arg2);
			break;

		case TASK_ID:
			String id = arg0.getPathSegments().get(1);
			count = datab.delete(DATABASE_TABLE, TaskContract.Task._ID + " = " + id + (!TextUtils.isEmpty(arg1) ? " AND (" + arg1 + ")" : ""), arg2);
			break;

		default:
			throw new IllegalArgumentException("unknown uri" + arg0);
		}
		getContext().getContentResolver().notifyChange(arg0, null);
		return count;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#getType(android.net.Uri)
	 */
	@Override
	public String getType(Uri uri)
	{
		switch(uri_matcher.match(uri))
		{
		case TASK_LIST:
			return TaskContract.Task.CONTENT_DIR_TYPE;

		case TASK_ID:
			return TaskContract.Task.CONTENT_ITEM_TYPE;

		default:
			throw new IllegalArgumentException("unsupported uri: " + uri);
		}
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
	 */
	@Override
	public Uri insert(Uri uri, ContentValues values)
	{
		// add a new book
		long row_id = datab.insert(DATABASE_TABLE, "", values);

		if(row_id > 0)
		{
			Uri _uri = ContentUris.withAppendedId(TaskContract.Task.CONTENT_URI, row_id);
			getContext().getContentResolver().notifyChange(_uri, null);
			return _uri;
		}
		else
		{
			throw new SQLException("failed to insert row into " + uri);
		}
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#onCreate()
	 */
	@Override
	public boolean onCreate()
	{
		Context context = getContext();
		DatabaseHelper db_helper = new DatabaseHelper(context);
		datab = db_helper.getWritableDatabase();

		return (datab == null ? false : true);
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
	 */
	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) 
	{
		SQLiteQueryBuilder sql_builder = new SQLiteQueryBuilder();
		sql_builder.setTables(DATABASE_TABLE);

		if(uri_matcher.match(uri) == TASK_ID)
		{
			sql_builder.appendWhere(TaskContract.Task._ID + " = " + uri.getPathSegments().get(1));
		}

		if(sortOrder == null || sortOrder == "")
		{
			sortOrder = TaskContract.Task.TODAY + " DESC";
		}

		Cursor cursor = sql_builder.query(datab, projection, selection, selectionArgs, null, null, sortOrder);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);

		return cursor;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[])
	 */
	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
	{
		int count = 0;

		switch(uri_matcher.match(uri))
		{
		case TASK_LIST:
			count = datab.update(DATABASE_TABLE, values, selection, selectionArgs);
			break;

		case TASK_ID:
			count = datab.update(
					DATABASE_TABLE,
					values,
					TaskContract.Task._ID + " = " + uri.getPathSegments().get(1) + 
					(!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : ""),
					selectionArgs);

		default:
			throw new IllegalArgumentException("unknown uri: " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}
	

}